//
//  UITabBar+Extention.m
//  haoshuimian365
//
//  Created by mc on 2018/3/16.
//  Copyright © 2018年 CZJ. All rights reserved.
//

#import "UITabBar+Extention.h"
#define TabbarItemNums 4.0
@implementation UITabBar (Extention)

//显示红点
- (void)showBadgeOnItmIndex:(int)index{
    [self removeBadgeOnItemIndex:index];
    //新建小红点
    UIView *bview = [[UIView alloc]init];
    bview.tag = 888+index;
    bview.layer.cornerRadius = 8;
    bview.clipsToBounds = YES;
    if (@available(iOS 10.0,*)) {
        bview.backgroundColor = self.selectedItem.badgeColor;
    }else{
        bview.backgroundColor = [UIColor redColor];
    }
    
    CGRect tabFram = self.frame;
    
    float percentX = (index+0.6)/TabbarItemNums;
    CGFloat x = ceilf(percentX*tabFram.size.width);
    CGFloat y = ceilf(0.1*tabFram.size.height);
    bview.frame = CGRectMake(x-3, y, 16, 16);
//    [self addSubview:bview];
    [self bringSubviewToFront:bview];
}

- (void)showBadgeOnItmIndex:(int)index withContent:(NSString *)content{
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    //新建小红点
    UILabel *numLabel = [UILabel lableWithText:content colorString:@"FFFFFF" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
    numLabel.backgroundColor = [UIColor colorWithString:@"FB4842"];
    numLabel.layer.cornerRadius = 8.0;//圆形
    numLabel.layer.masksToBounds = YES;
    numLabel.tag = 888 + index;

    CGFloat tabWidth = self.frame.size.width;
    CGFloat tabHeight = self.frame.size.height;
    float percentX = (index+0.55) / TabbarItemNums;
    
    CGFloat x = ceilf(percentX * tabWidth);
    CGFloat y = ceilf(0.1 * tabHeight)-viewPix(4)-iPhoneXMargin(4);

    NSInteger count = [content integerValue];
    if(count<10){
        numLabel.frame = CGRectMake(x, y, 16, 16);
        
    }else if (count<100){
        numLabel.frame = CGRectMake(x, y, 24, 16);
        
    }else{
        numLabel.frame = CGRectMake(x, y, 35, 16);
    }
    [self addSubview:numLabel];
}

//隐藏红点
-(void)hideBadgeOnItemIndex:(int)index{
    [self removeBadgeOnItemIndex:index];
}
//移除控件
- (void)removeBadgeOnItemIndex:(int)index{
    for (UIView*subView in self.subviews) {
        if (subView.tag == 888+index) {
            [subView removeFromSuperview];
        }
    }
}

@end
